package com.shuangfeidasan.service.ums.impl;

import com.shuangfeidasan.model.ums.UmsPermission;
import com.shuangfeidasan.model.ums.UmsRole;
import com.shuangfeidasan.model.ums.UmsRolePermissionRelation;
import com.shuangfeidasan.service.ums.UmsPermissionService;
import com.shuangfeidasan.service.ums.UmsRolePermissionRelationService;
import com.shuangfeidasan.service.ums.UmsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description 动态权限数据获取服务类
 * @Author JunWEI
 * @Date 2022/1/22
 */
@Service
public class DynamicSecurityService {
    @Autowired
    UmsRoleService umsRoleService;
    @Autowired
    UmsPermissionService umsPermissionService;
    @Autowired
    UmsRolePermissionRelationService umsRolePermissionRelationService;

    /**
     * 加载资源ANT通配符和资源对应MAP
     */
    public Map<String, List<ConfigAttribute>> loadDataSource() {
        Map<String, List<ConfigAttribute>> map = new ConcurrentHashMap<>();
        List<UmsRole> umsRoleList = umsRoleService.queryAll(new UmsRole());
        for (UmsRole umsRole : umsRoleList) {
            UmsRolePermissionRelation umsRolePermissionRelation = new UmsRolePermissionRelation();
            umsRolePermissionRelation.setRoleId(umsRole.getId());
            List<UmsRolePermissionRelation> umsRolePermissionRelationList = umsRolePermissionRelationService.queryAll(umsRolePermissionRelation);

            List<UmsPermission> umsPermissionList = umsRolePermissionRelationList.stream()
                    .map(item -> umsPermissionService.queryById(item.getPermissionId()))
                    .collect(Collectors.toList());

            for (UmsPermission umsPermission : umsPermissionList) {
                String pattern = umsPermission.getUri() + "/" + umsPermission.getMethod();
                List<ConfigAttribute> configAttributes = map.getOrDefault(pattern, new ArrayList<>());
                configAttributes.add(new org.springframework.security.access.SecurityConfig(umsRole.getName()));
                map.put(pattern, configAttributes);
            }
        }
        return map;
    }
}
